package com.anmingle.pswb.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * @author 安明乐
 */
@ControllerAdvice
public class GlobalException {


    private record ResponseResult(
            Integer code,
            String msg
    ){}


    @ResponseBody
    @ExceptionHandler
    public ResponseResult handlerException(Exception e) {

        // 打印堆栈，以供调试
        e.printStackTrace();

        ResponseResult responseResult;
        // 不同异常返回不同状态码
        // 如果是未登录异常
        if (e instanceof NotLoginException) {
            NotLoginException ee = (NotLoginException) e;
            responseResult = new ResponseResult(ee.getCode(),"用户未登录: "+ee.getMessage());
        }
        // 如果是角色异常
        else if(e instanceof NotRoleException) {
            NotRoleException ee = (NotRoleException) e;
            responseResult = new ResponseResult(ee.getCode(),"无此角色：" + ee.getRole());
        }
        // 如果是权限异常
        else if(e instanceof NotPermissionException) {
            NotPermissionException ee = (NotPermissionException) e;
            responseResult = new ResponseResult(ee.getCode(),"无此权限：" + ee.getMessage());
        } else {	// 普通异常, 输出：500 + 异常信息
            responseResult = new ResponseResult(50000,e.getMessage());
        }

        // 返回给前端
        return responseResult;
    }

}
